package com.siqi.hr.common.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.siqi.hr.common.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by ChenLei on 2016/10/11.
 */
@Controller
@RequestMapping(value = "OSS")
public class OssController {

    private String endpoint = Constants.OSS_ENDPOINT;
    private String accessKeyId = Constants.OSS_ACCESS_KEY_ID;
    private String accessKeySecret = Constants.OSS_ACCESS_KEY_SECRET;
    private String bucketName = Constants.OSS_BUCKET_NAME;

    /**
     * 图片上传至云存储，支持多图
     * @author ChenL
     * @param upfile
     * @param pw
     */
    @RequestMapping(value = "uploadImage")
    public void uploadImage(@RequestParam(value = "upfile", required = false) MultipartFile[] upfile, PrintWriter pw){
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        boolean exists = ossClient.doesBucketExist(bucketName);

        Map<String,String> map = new HashMap<String, String>();
        if (upfile != null && upfile.length > 0){
            //循环获取file数组中得文件
            for(int i = 0;i<upfile.length;i++){
                MultipartFile file = upfile[i];
                String original = file.getOriginalFilename();
                String type = original.substring(original.lastIndexOf("."));
                String title = UUID.randomUUID().toString() + type;
                Long size = file.getSize();
                String url = Constants.OSS_URL + Constants.OSS_PATH_IMAGES + title;
                //返回对象
                try {
                    if(exists){
                        ossClient.putObject(bucketName, Constants.OSS_PATH_IMAGES + title, file.getInputStream());
                        map.put("original",original);
                        map.put("size",size.toString());
                        map.put("state","SUCCESS");
                        map.put("title",title);
                        map.put("type",type);
                        map.put("url",url);
                    }else{
                        map.put("state","OSS队列不存在,上传失败!");
                    }
                }catch (Exception e){
                    map.put("state","上传失败!");
                    e.printStackTrace();
                }
            }
        }
        ossClient.shutdown();
        System.out.println(JSON.toJSONString(map));
        pw.print(JSON.toJSONString(map));
    }

}
